package com.thirtydays.frame.base

import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.Color
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.os.CountDownTimer
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewStub
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.azhon.appupdate.manager.DownloadManager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ToastUtils
import com.gyf.immersionbar.ImmersionBar
import com.thirtydays.frame.R
import com.thirtydays.frame.base.bean.EventMessage
import com.thirtydays.frame.constant.*
import com.thirtydays.frame.data.DataManager
import com.thirtydays.frame.databinding.*
import com.thirtydays.frame.module.login.view.LoginActivity
import com.thirtydays.frame.util.DownTimeUtils
import com.thirtydays.frame.util.ext.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.lang.reflect.ParameterizedType

/**
 * @创建者：小垚
 * @时间：2021/7/2212:26
 * @描述：Activity的基类
 */
abstract class BaseActivity<VM : BaseViewModel, SV : ViewBinding> : AppCompatActivity() {

    open val mAppViewModel: AppViewModel by lazy { getAppViewModel() }
    lateinit var mViewModel: VM
    lateinit var mViewBinding: SV
    lateinit var mBaseViewBinding: ActivityBaseBinding
    lateinit var mLoadingViewBinding: LayoutLoadingViewBinding
    lateinit var mLoadingErrorBinding: LayoutLoadingErrorBinding

    lateinit var mImmersionBar: ImmersionBar
    var mLoadingView: View? = null
    var mErrorView: View? = null
    var isBar = true
    var isDarkFont = true
    var mAnimationDrawable: AnimationDrawable? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val type = javaClass.genericSuperclass as ParameterizedType
        val clazz1 = type.actualTypeArguments[0] as Class<VM>
        mViewModel = ViewModelProvider(this)[clazz1]

        val clazz2 = if (type.actualTypeArguments.size <= 1) {
            ActivityBaseRecycleViewBinding::class.java
        } else {
            type.actualTypeArguments[1] as Class<SV>
        }
        val method = clazz2.getMethod("inflate", LayoutInflater::class.java)
        mViewBinding = method.invoke(null, layoutInflater) as SV


        initCreate(savedInstanceState)
        addBaseContentView(mViewBinding.root)

        registerEvent() //设置竖屏
        //        ScreenUtils.setPortrait(this)
    }

    open fun initCreate(savedInstanceState: Bundle?) {

    }

    private fun addBaseContentView(layoutResID: View) {
        mBaseViewBinding = ActivityBaseBinding.inflate(layoutInflater)
        setContentView(mBaseViewBinding.root)

        val layoutParams = RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)
        mViewBinding.root.layoutParams = layoutParams
        mBaseViewBinding.container.addView(mViewBinding.root)

        initViewModel()
        init()
        initStatusBar()
        initListener()
        initRequest()

        //        KeyboardUtils.fixAndroidBug5497(this)
    }

    abstract fun init()

    open fun initListener() {

    }

    open fun initRequest() {

    }

    open fun initViewModel() {
        mViewModel.run {
            mIsShowStatus.observe(this@BaseActivity) {
                it?.run {
                    when (index) {
                        BASE_SHOW_LOADING -> {
                            showLoading(tip)
                        }
                        BASE_SHOW_CONTENT -> {
                            showContent()
                        }
                        BASE_SHOW_ERROR   -> {
                            showError()
                        }
                        BASE_HIDE_LOADING -> {
                            hideLoading()
                        }
                        BASE_TO_LOGIN     -> {
                            toLogin()
                        }
                    }
                }
            }
        }
        initObserve()
    }

    open fun toLogin() {
        DataManager.clearLogins()
        pop<LoginActivity>()
        ActivityUtils.getActivityList().forEachIndexed { _, activity ->
            if (activity !is LoginActivity) {
                ActivityUtils.finishActivity(activity)
            }
        }
    }

    open fun initObserve() {

    }

    /**
     * 跳转登录
     */
    open fun showLogin() {

    }

    /**
     * 设置标题
     */
    fun setToolbar(title: String) {
        mBaseViewBinding.toolbar.setTitle(title)
    }

    /**
     * 隐藏标题
     */
    fun hideToolBar() {
        mBaseViewBinding.toolbar.gone()
    }

    /**
     * 显示加载中
     */
    var loadNum = 0
    open fun showLoading(tip: String = "") {
        loadNum++
        if (mLoadingView == null) {
            mLoadingView = findViewById<ViewStub>(R.id.vs_loading).inflate()
            mLoadingViewBinding = LayoutLoadingViewBinding.bind(mLoadingView!!)
            mAnimationDrawable = mLoadingViewBinding.imgProgress.drawable as AnimationDrawable
            if (tip.isNotEmpty()) {
                mLoadingViewBinding.textTip.text = tip
            }
        } else {
            mLoadingView?.let {
                it.visible()
            }
        }

        mAnimationDrawable?.let {
            if (!it.isRunning) {
                it.start()
            }
        }

        mBaseViewBinding.container.isClick = true
    }

    /**
     * 隐藏加载中
     */
    open fun hideLoading() {
        loadNum--
        if (loadNum <= 0) {
            mLoadingView?.post {
                mLoadingView?.gone()
            }

            mAnimationDrawable?.let {
                if (it.isRunning) {
                    it.stop()
                }
            }
            mBaseViewBinding.container.isClick = false
        }
    }


    /**
     * 显示错误页面
     */
    open fun showError() {
        hideLoading()
        if (mErrorView == null) {
            mErrorView = findViewById<ViewStub>(R.id.vs_error_refresh).inflate()
            mLoadingErrorBinding = LayoutLoadingErrorBinding.bind(mErrorView!!)
            mLoadingErrorBinding.clError.setOnClickListener {
                onToRequest()
            }
        } else {
            mErrorView?.visible()
        }

        if (mViewBinding.root.isVisible) {
            mViewBinding.root.gone()
        }
    }

    /**
     * 显示正常页面
     */
    open fun showContent() {
        mErrorView?.let {
            if (it.isVisible) {
                it.gone()
            }
        }

        if (mViewBinding.root.isGone) {
            mViewBinding.root.visible()
        }
    }

    /**
     * 错误界面的点击事件
     */
    open fun onToRequest() {
        initRequest()
    }

    /**
     * 状态栏管理器
     */
    private fun initStatusBar() {
        if (isBar) {
            ImmersionBar.with(this).transparentStatusBar().statusBarDarkFont(isDarkFont).init()
        } else {
            ImmersionBar.with(this).statusBarColor(R.color.colorPrimaryDark).fitsSystemWindows(true).statusBarDarkFont(isDarkFont).init()
        }
    }

    /**
     * 消息、事件接收回调
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun handleEvent(msg: EventMessage) {

    }

    /**
     * 设置Adapter
     */
    open fun setRvAdapter(recycle: RecyclerView, manager: RecyclerView.LayoutManager, adapter: RecyclerView.Adapter<*>) {
        recycle.layoutManager = manager
        recycle.adapter = adapter
    }

    open fun emptyView(): LayoutLoadingEmptyBinding {
        return LayoutLoadingEmptyBinding.inflate(layoutInflater, null, false)
    }

    //开启倒计时
    open var downTime: CountDownTimer? = null
    open fun downTime(textView: TextView) {
        downTime = DownTimeUtils.startSingleDownTime(60 * 1000L, { millis, _ ->
            ThreadUtils.runOnUiThread {
                textView.text = "${millis / 1000}s"
                textView.isEnabled = false
            }
        }) {
            ThreadUtils.runOnUiThread {
                textView.text = "获取验证码"
                textView.isEnabled = true
            }
        }
    }

    override fun onDestroy() {
        downTime?.let {
            it.cancel()
        }
        super.onDestroy()
        unregisterEvent()
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        if (newConfig.fontScale != 1f) {
            resources
        }
    }

    /**
     * 禁止改变字体大小
     */
    override fun getResources(): Resources? {
        val res: Resources = super.getResources()
        val config = Configuration()
        config.setToDefaults()
        createConfigurationContext(config)
        return res
    }

    fun showToast(message: Int) {
        ToastUtils.getDefaultMaker()
            .setBgResource(R.drawable.trtcliveroom_message_background)
            .setTextColor(Color.WHITE)
            .setGravity(Gravity.CENTER, 0, 0)
            .setMode(ToastUtils.MODE.DARK)
            .setDurationIsLong(false)
            .show(getString(message))
    }

    fun showToast(message: String) {
        ToastUtils.getDefaultMaker()
            .setBgResource(R.drawable.trtcliveroom_message_background)
            .setTextColor(Color.WHITE)
            .setGravity(Gravity.CENTER, 0, 0)
            .setMode(ToastUtils.MODE.DARK)
            .setDurationIsLong(false)
            .show(message)
    }

    fun showLongToast(message: String) {
        ToastUtils.getDefaultMaker()
            .setBgResource(R.drawable.trtcliveroom_message_background)
            .setTextColor(Color.WHITE)
            .setGravity(Gravity.CENTER, 0, 0)
            .setMode(ToastUtils.MODE.DARK)
            .setDurationIsLong(true)
            .show(message)
    }

    fun showLongToast(message: Int) {
        ToastUtils.getDefaultMaker()
            .setBgResource(R.drawable.trtcliveroom_message_background)
            .setTextColor(Color.WHITE)
            .setGravity(Gravity.CENTER, 0, 0)
            .setMode(ToastUtils.MODE.DARK)
            .setDurationIsLong(true)
            .show(getString(message))
    }

    /**
     * 下载apk
     */
    fun downApk(versionName: String, updateContent: String, url: String) {
        DownloadManager.getInstance(this)
            .setApkVersionName(versionName)
            .setApkDescription(updateContent)
            .setShowNewerToast(true)
            .setApkName("${getString(R.string.app_name)}${versionName}.apk")
            .setApkUrl(url)
            .setSmallIcon(R.mipmap.ic_launcher)
            .download()
    }
}
